/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.action;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author THANH
 */
public class UploadAction implements Action {

    public void exe(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String contentType = request.getContentType();
        PrintWriter out = response.getWriter();
        if (contentType != null) {
            DataInputStream dis = new DataInputStream(request.getInputStream());
            int dataLenght = request.getContentLength();
            out.print(request.getInputStream().toString());
            byte dataBytes[] = new byte[dataLenght];
            int byteRead = 1024;
            int totalRead = 0;
            while (totalRead < dataLenght) {
                byteRead = dis.read(dataBytes, totalRead, dataLenght);
                totalRead += byteRead;
            }
            String file = new String(dataBytes);
            
//            String saveFile = file.substring(file.indexOf("filename=\"") + 10);
//            saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
//            saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));

            int lastIndex = contentType.lastIndexOf("=");
            String boundary = contentType.substring(lastIndex + 1, contentType.length());

            int pos;
            pos = file.indexOf("filename=\"");

            pos = file.indexOf("\n", pos) + 1;

            pos = file.indexOf("\n", pos) + 1;

            pos = file.indexOf("\n", pos) + 1;

            int boundaryLocation = file.indexOf(boundary, pos) - 4;
//            int startPos = ((file.substring(0, pos)).getBytes()).length;
//            int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

//            FileOutputStream fileOut = new FileOutputStream(saveFile);
            //File fileOut = new File("fileUpload/"+request.getParameter("file"));
            FileOutputStream fileOut = new FileOutputStream(request.getParameter("file"));
            
//            fileOut.write(dataBytes, startPos, (endPos - startPos));
            fileOut.flush();
            fileOut.close();
            
            out = response.getWriter();
            out.println("File saved as " );
        }
        out.println("File saved as ");
    }
}
